package com.example.mychat.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.mychat.Adapter.ChatitemAdapter;
import com.example.mychat.Bean.Chatitem;
import com.example.mychat.Bean.Msg;
import com.example.mychat.Bean.User;
import com.example.mychat.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ListView chatitemlv;
    ChatitemAdapter adapter;
    List<Chatitem> chatitemList=new ArrayList<>();//数据源
    List<User> userList=new ArrayList<>();
    List<Msg> msgList=new ArrayList<>();
    int myid;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initData();
        initView(view);
        setListener();
        return view;
    }

    private void setListener() {
    }

    private void initData() {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        myid=sp.getInt("myid",-1);
        userList= LitePal.where("id != ?", myid+"").find(User.class);
        for (User u:userList){
            msgList=getChatContent(u);
            if (msgList.size()!=0){
                Msg m=msgList.get(msgList.size()-1);
                Chatitem chatitem=new Chatitem(u.getUserimg(),u.getName(),m.getContent(),m.getDate());
                chatitemList.add(chatitem);
            }
        }
    }

    private List<Msg> getChatContent(User u) {//获取聊天框内容
        List<Msg> msgs = new ArrayList<>();
        for (Msg m : LitePal.findAll(Msg.class)) {
            boolean a = myid == m.getReceive_id() && u.getId() == m.getSend_id();
            boolean b = u.getId() == m.getReceive_id() && myid == m.getSend_id();
            if (a || b) {
                msgs.add(m);
            }
        }
        return msgs;
    }

    private void initView(View view){
        chatitemlv=view.findViewById(R.id.chatitemlv);
        adapter=new ChatitemAdapter(getContext(),R.layout.chat_item,chatitemList);
        chatitemlv.setAdapter(adapter);
    }
}